package fast;

import java.io.*;
import java.net.*;

/**
 * TCPTalker Class
 * 
 * Removes entries from a buffer, establishes where these entries need to be
 * sent and opens a TCP connection to a remote host to send the buffer data.
 * Must be run as a thread.
 * 
 * @version 0.1
 * @author Adam Bell
 * @date 17/12/2009
 */
public class TCPTalker implements Runnable {

	private Buffer talkBuffer;
	private Socket s;

	/**
	 * Constructor
	 * 
	 * @param port
	 *            The default port to send to
	 * @param b
	 *            The buffer to read from
	 */
	public TCPTalker(Buffer b) {
		this.talkBuffer = b;
	}

	/**
	 * Thread actions
	 */
	public void run() {
		String[] packet;
		String address;
		int port;
		int id;
		String command;
		String data;

		while (true) {
			s = null;

			try {
				// grab a packet to send from the talk buffer. Split it into
				// s[0] address, s[1] port, s[2] id, s[3] command, s[4] data
				packet = talkBuffer.remove().split("\\|");

				address = packet[0];
				port = Integer.valueOf(packet[1]);
				id = Integer.valueOf(packet[2]);
				command = packet[3];
				data = "";

				if (packet.length > 4) {
					data = packet[4];
				}

				// create a new socket
				s = new Socket(address, port);

				// bind a buffered outputstream to the socket
				BufferedOutputStream bout = new BufferedOutputStream(s
						.getOutputStream());

				// build string to send
				String out = id + "|" + command + "|" + data;

				// convert to byte array and send
				bout.write(out.getBytes());
				bout.flush();

				s.close();
				// MAGIC NUMBER
				// sleeps after a send for 10milliseconds, to prevent
				// master from being swamped with connection attempts
				Thread.sleep(5);

			} catch (InterruptedException e) {
				System.out.print(e);
			} catch (UnknownHostException e) {
				System.out.print(e);
			} catch (IOException e) {
				System.out.print(e);
			}// try
		}// while
	}// run()
}
